﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.ComponentModel;
using System.Collections.Specialized;
using System.Data;
using System.Windows.Threading;
using Microsoft.Win32;

namespace Xinnos.Lca.Yacht.Analyzer.View
{
    /// <summary>
    /// ObjectRatePanel.xaml에 대한 상호 작용 논리
    /// </summary>
    public partial class ObjectRatePanel : UserControl
    {
        private AssessmentViewModel mViewModel = null;
        private WorkBreakdownStructuresViewModel mStructures = null;
        public ObjectRatePanel()
        {
            InitializeComponent();
            mStructures = WorkBreakdownStructuresViewModel.GetInstance();

            Initialize();

            if (null == mViewModel)
            {
                mViewModel = AssessmentViewModel.GetInstance();
                this.DataContext = mViewModel;
            }
        }

        private void Initialize()
        {
            ConfigurationViewModel _configuration = ConfigurationViewModel.GetInstance();
            WorkBreakdownStructureGroupViewModel _objects = null;
            foreach (WorkBreakdownStructureGroupViewModel _group in mStructures.Groups)
            {
                if (_configuration.Object == _group.Name) _objects = _group;
                else
                {
                    DataGridTextColumn _column = new DataGridTextColumn();
                    _column.Header = _group.Name;
                    _column.Width = new DataGridLength(1, DataGridLengthUnitType.Star);
                    int _index = mStructures.Groups.IndexOf(_group);
                    if (null != _objects) _index--;
                    Binding _binding = new Binding(string.Format("Sequences[{0}].Name", _index));
                    _column.Binding = _binding;
                    _column.IsReadOnly = true;
                    _column.ElementStyle = FindResource("cellStyle") as Style;
                    _column.CanUserSort = true;
                    dataGridAssessment.Columns.Add(_column);
                }
            }
            if (null != _objects) AppendObjectColumns(_objects.WorkBreakdownStructures, 0);
            if (0 < dataGridAssessment.Columns.Count) dataGridAssessment.Columns[0].SortDirection = ListSortDirection.Ascending;
        }
        private int AppendObjectColumns(IEnumerable<WorkBreakdownStructureViewModel> enumerable, int nIndex)
        {
            int _index = nIndex;
            foreach (ObjectViewModel _object in enumerable)
            {
                DataGridTextColumn _column = new DataGridTextColumn();
                _column.Header = _object.Name;
                _column.Width = new DataGridLength(1, DataGridLengthUnitType.Star);
                Binding _binding = new Binding(string.Format("Rates[{0}].Rate", _index));
                _column.Binding = _binding;
                _column.IsReadOnly = true;
                _column.ElementStyle = FindResource("cellStyle") as Style;
                dataGridAssessment.Columns.Add(_column);
                _index++;
                if (0 < _object.Children.Count) _index = AppendObjectColumns(_object.Children, _index);
            }
            return _index;
        }

        public bool CanExport()
        {
            return 0 < mViewModel.Rows.Count;
        }

        public void Export()
        {
            SaveFileDialog _dialog = new SaveFileDialog();
            _dialog.DefaultExt = ".xlsx";
            _dialog.Filter = "Microsoft Excel(*.xlsx)|*.xlsx|Microsoft Excel 97 - 2003(*.xls)|*.xls|모든 파일|*.*";
            _dialog.Title = "Microsoft Excel로 내보내기";
            _dialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            if (true == _dialog.ShowDialog())
            {
                BackgroundWorker _worker = new BackgroundWorker();
                _worker.WorkerSupportsCancellation = false;
                _worker.WorkerReportsProgress = false;
                _worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(OnRunWorkerCompletedExport);
                _worker.DoWork += new DoWorkEventHandler(OnDoWorkExport);
                _worker.RunWorkerAsync(_dialog.FileName);
            }
        }

        private DataTable GetDataTable()
        {
            DataTable _table = new DataTable("Assessment");
            foreach (DataGridTextColumn _header in dataGridAssessment.Columns)
            {
                Binding _binding = _header.Binding as Binding;
                DataColumn _column = new DataColumn(_binding.Path.Path, typeof(string));
                this.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(delegate
                { _column.Caption = _header.Header as string; }));
                _table.Columns.Add(_column);
            }
            foreach (RateRowViewModel _rate in mViewModel.Rows)
            {
                DataRow _row = _table.NewRow();
                for (int i = 0; i < _rate.Sequences.Count; i++) _row[string.Format("Sequences[{0}].Name", i)] = _rate.Sequences[i].Name;
                for (int i = 0; i < _rate.Rates.Count; i++) _row[string.Format("Rates[{0}].Rate", i)] = _rate.Rates[i].Rate;
                _table.Rows.Add(_row);
            }
            return _table;
        }

        private void OnDoWorkExport(object sender, DoWorkEventArgs e)
        {
            string _path = e.Argument as string;
            DataTable _table = GetDataTable();
            TableExporter _exporter = new TableExporter();
            _exporter.ExportToExcel(_table, _path);
        }

        private void OnRunWorkerCompletedExport(object sender, RunWorkerCompletedEventArgs e)
        {
            if (null == e.Error) MessageBox.Show("Microsoft Excel 파일로 출력했습니다.");
            else MessageBox.Show(e.Error.Message, "오류");
        }
    }
}